package com.zyf.connotation.ui

import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.*
import cn.feng.skin.manager.base.SkinBaseActivity
import com.bumptech.glide.Glide
import com.zyf.connotation.R
import com.zyf.connotation.bean.Comments
import com.zyf.connotation.bean.Connotation
import com.zyf.connotation.bean.DiggUser
import com.zyf.connotation.presenter.ConnotationPresenter
import com.zyf.connotation.utils.DateUtils
import com.zyf.connotation.view_interface.IConnotationView
import fm.jiecao.jcvideoplayer_lib.JCMediaManager
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerManager
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
import kotlinx.android.synthetic.main.activity_connotation_info.*
import kotlinx.android.synthetic.main.comment_item.view.*
import kotlinx.android.synthetic.main.content_connotation_info.*
import kotlinx.android.synthetic.main.info_image_head_item.view.*
import kotlinx.android.synthetic.main.rec_item.*

class ConnotationInfoActivity : SkinBaseActivity(),IConnotationView {
    var presenter: ConnotationPresenter = ConnotationPresenter(this)
    var diggUser:DiggUser? = null
    var comments:ArrayList<Comments.RecentComments> = ArrayList()
    var top_count = 0
    var comment_count = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_connotation_info)
        setSupportActionBar(toolbar)
        supportActionBar?.setHomeButtonEnabled(true)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        dynamicAddSkinEnableView(toolbar, "background", R.color.colorPrimary)
        dynamicAddSkinEnableView(fab, "backgroundTint", R.color.colorAccent)
        initData()
    }

    private fun initData() {
        var data = intent.getSerializableExtra("data") as Connotation.Data
        var url = intent.getStringExtra("url")
        var play = intent.getBooleanExtra("play",false)
        fab.setOnClickListener {
            showComment(data.group.group_id)
        }
        comment_count = data.group.comment_count
        if(data.group?.is_anonymous!=null&&data.group?.is_anonymous){
            anonymous.visibility = View.VISIBLE
            user_layout?.visibility = View.GONE
        }else{
            anonymous?.visibility = View.GONE
            user_layout?.visibility = View.VISIBLE
            name?.text = data.group.user.name
            head_img?.setImageURI(data.group.user.avatar_url)
        }
        if(data.group.is_neihan_hot) hot?.visibility = View.VISIBLE else hot?.visibility = View.INVISIBLE

        content?.text = data.group.content
        category_name?.text = data.group.category_name
        fabulous?.text = ""+data.group.digg_count
        if(data.group.user_digg == 1){
            fabulous_image?.setImageResource(R.drawable.fabulous)
            fabulous?.setTextColor(resources.getColor(R.color.textColor))
        }else{
            fabulous_image?.setImageResource(R.drawable.no_fabulous)
            fabulous?.setTextColor(resources.getColor(R.color.noColor))
        }
        stampede?.text = ""+data.group.bury_count
        if(data.group.user_bury == 1){
            stampede_image?.setImageResource(R.drawable.stampede)
            stampede?.setTextColor(resources.getColor(R.color.textColor))
        }else{
            stampede_image?.setImageResource(R.drawable.no_stampede)
            stampede?.setTextColor(resources.getColor(R.color.noColor))
        }
        message?.text = ""+data.group.comment_count
        if(TextUtils.isEmpty(data.group.content)){
            content?.visibility = View.GONE
        }
        if(!TextUtils.isEmpty(data.group.mp4_url)){
            if(data.group.video_height>480){
                videoplayer?.widthRatio = 4
                videoplayer?.heightRatio = 3
            }else{
                videoplayer?.widthRatio = 16
                videoplayer?.heightRatio = 9
            }
            Glide.with(this@ConnotationInfoActivity).load(data.group.large_cover.url_list[0].url).into(videoplayer?.thumbImageView)
            videoplayer?.setUp(data.group.mp4_url, JCVideoPlayerStandard.SCREEN_LAYOUT_LIST,"")
            if(!TextUtils.isEmpty(url)&&url.equals(data.group.mp4_url)&&play){
                videoplayer.prepareMediaPlayer()
            }
        }else{
            videoplayer.visibility = View.GONE
        }
        fabulous_layout?.setOnClickListener {
            if(data.group.user_digg ==1||data.group.user_bury ==1){
                Toast.makeText(applicationContext,"您已经顶过", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            presenter.netFabulous(0,"digg",data)
        }
        stampede_layout?.setOnClickListener {
            if(data.group.user_digg ==1||data.group.user_bury ==1){
                Toast.makeText(applicationContext,"您已经顶过", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            presenter.netFabulous(0,"bury",data)
        }
        var layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        recycle.layoutManager = layoutManager
        digg_count.text = ""+data.group.digg_count+"人赞过"
        recycle_comment.layoutManager =  LinearLayoutManager(this)
        presenter.getDiggUser(DiggUser::class.java,data.group.group_id)
        presenter.getComments(Comments::class.java,data.group.group_id,0)
        nestedscroll.setOnScrollChangeListener {
            v: @ParameterName(name = "v") NestedScrollView?,
            scrollX: @ParameterName(name = "scrollX") Int,
            scrollY: @ParameterName(name = "scrollY") Int,
            oldScrollX: @ParameterName(name = "oldScrollX") Int,
            oldScrollY: @ParameterName(name = "oldScrollY") Int ->
            if (scrollY == (v?.getChildAt(0)?.measuredHeight!!.minus(v?.measuredHeight) )) {
                if(comment_count>comments.size){
                    presenter.getComments(Comments::class.java,data.group.group_id,comments.size-top_count)
                }
            }

           /* if(!TextUtils.isEmpty(data.group.mp4_url)){
                videoplayer.startWindowTiny()
            }*/
        }
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if(item?.itemId==android.R.id.home){
            if (android.os.Build.VERSION.SDK_INT > 20)
                finishAfterTransition()
            else
                finish()
        }
        return super.onOptionsItemSelected(item)
    }
    inner class HeadImageAdapter:RecyclerView.Adapter<HeadImageViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): HeadImageViewHolder {
            return HeadImageViewHolder(View.inflate(this@ConnotationInfoActivity,R.layout.info_image_head_item,null))
        }

        override fun getItemCount(): Int {
            return  if(diggUser?.users?.size!!>5) 5 else diggUser?.users?.size!!
        }

        override fun onBindViewHolder(holder: HeadImageViewHolder?, position: Int) {
            holder?.imageHead?.setImageURI(diggUser?.users?.get(position)?.avatar_url)
        }
    }
    inner class HeadImageViewHolder(itemView: View?): RecyclerView.ViewHolder(itemView){
        var imageHead = itemView?.item_head_img
    }

    override fun <T> DataList(t: T?, isTop: Boolean) {
        if(isTop){
            // 获取点赞用户
            diggUser = t as DiggUser
            if(diggUser?.users?.size == 0){
                user_digg_layout.visibility = View.GONE
                return
            }
            recycle.adapter = HeadImageAdapter()
            return
        }
        if(t is Comments){
            //获取评论
            var comment = t
            comment?.top_comments?.forEach {
                it.type=1
                top_count +=1
            }
            comments.addAll(comment?.top_comments)
            comments.addAll(comment?.recent_comments)
            if(comments.size == 0){
                comment_empty.visibility = View.VISIBLE
                recycle_comment.visibility = View.GONE
                return
            }
            recycle_comment.adapter = CommentAdapter()
            return
        }
        if(t is Comments.RecentComments){
            //发表评论
            comments.add(t)
            recycle_comment.adapter = CommentAdapter()
            return
        }
    }

    override fun fabulous(position: Int, check: String) {
        if(check.equals("digg")){
            fabulous_image?.setImageResource(R.drawable.stampede)
            fabulous?.setTextColor(resources.getColor(R.color.textColor))
            fabulous?.text = ""+(fabulous?.text.toString().toInt()+1)
        }else{
            stampede_image?.setImageResource(R.drawable.stampede)
            stampede?.setTextColor(resources.getColor(R.color.textColor))
            stampede?.text = ""+(stampede?.text.toString().toInt()+1)
        }
    }
    inner class CommentAdapter:RecyclerView.Adapter<CommentViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CommentViewHolder {
            return CommentViewHolder(View.inflate(this@ConnotationInfoActivity,R.layout.comment_item,null))
        }

        override fun getItemCount(): Int {
            return  comments.size
        }

        override fun onBindViewHolder(holder: CommentViewHolder?, position: Int) {
            var data = comments[position]
            if(position<top_count){
                holder?.title?.text = "热门评论（$top_count）"
            }else{
                var count = comment_count-top_count
                holder?.title?.text = "新鲜评论（$count）"
            }
            if(position>0 && data.type == comments[position-1].type){
                holder?.title?.visibility = View.GONE
            }else{
                holder?.title?.visibility = View.VISIBLE
            }
            holder?.comment_fabulous?.text = ""+data.digg_count
            holder?.comment_head_img?.setImageURI(data.avatar_url)
            holder?.comment_name?.text = data.user_name
            holder?.comment_time?.text = DateUtils.getStringformat(data.create_time)
            holder?.comment_content?.text = data.text
        }
    }
    inner class CommentViewHolder(itemView: View?): RecyclerView.ViewHolder(itemView){
        var title = itemView?.title
        var comment_fabulous_layout = itemView?.comment_fabulous_layout
        var comment_fabulous_image = itemView?.comment_fabulous_image
        var comment_content = itemView?.comment_content
        var comment_fabulous = itemView?.comment_fabulous
        var comment_head_img = itemView?.comment_head_img
        var comment_name = itemView?.comment_name
        var comment_time = itemView?.comment_time
    }

    var edit: EditText? = null
    var send: TextView? = null
    fun showComment(id:String) {
        val popupWindow_view = layoutInflater.inflate(R.layout.comment_edit, null, false)
        val popupWindow = PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true)
        //        popupWindow.setAnimationStyle(R.style.AppTheme);
        popupWindow.setBackgroundDrawable(BitmapDrawable())
        popupWindow.isOutsideTouchable = true
        popupWindow.softInputMode = PopupWindow.INPUT_METHOD_NEEDED
        popupWindow.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        popupWindow.showAtLocation(coord, Gravity.BOTTOM, 0, 0)
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        //得到InputMethodManager的实例
        if (imm.isActive) {
            //如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS)
            //关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
        edit = popupWindow_view.findViewById(R.id.edit_comment) as EditText
        send = popupWindow_view.findViewById(R.id.send_comment) as TextView
        send?.isEnabled = false
        send?.setOnClickListener {
            //发送评论
            //sendNetCommment(edit.text.toString())
            //presenter.sendComment(Comments.RecentComments::class.java,id,edit?.text.toString())
            Toast.makeText(this@ConnotationInfoActivity,"暂不支持评论",Toast.LENGTH_SHORT).show()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(edit?.windowToken, 0)
            popupWindow.dismiss()
        }
        edit?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (TextUtils.isEmpty(s)) {
                    send?.isEnabled = false
                }
                if (!TextUtils.isEmpty(s)) {
                    send?.isEnabled = true
                }
            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
    override fun onPause() {
        super.onPause()
        JCVideoPlayer.releaseAllVideos()
    }
    override fun onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun error(error: String) {
        Toast.makeText(this@ConnotationInfoActivity,error,Toast.LENGTH_SHORT).show()
    }
}
